//
//  LZMapLocationManager.m
//  laziz_Consumer
//
//  Created by xbnzd on 16/12/9.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMapLocationManager.h"
#import "LZRestaurantSearchCityView.h"
#import "LZAlertView.h"
#import "CitysModel.h"
#import "CityManager.h"

@interface LZMapLocationManager ()
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLGeocoder *geocoder;
@property (copy, nonatomic) LocationUpdateCompletion completionBlock;
@property (copy, nonatomic) LocationFailedBlock failedBlock;

@end

@implementation LZMapLocationManager

+ (instancetype) shareLocationManager
{
    static LZMapLocationManager *locationManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        locationManager = [[LZMapLocationManager alloc] init];
    });
    return locationManager;
}

- (id) init
{
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        _geocoder = [[CLGeocoder alloc] init];
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [_locationManager requestWhenInUseAuthorization];
        }
      
    }
    return self;
}

/* ************************ app启动时定位城市逻辑 ************************ */
- (void)appStartLocationServer {
    CitysModel *saveCityModel = [CitysModel getCityModel];
    
    if ([LZMapLocationManager shareLocationManager].isOpenLocation) {
        // 如果开启了定位

        if (saveCityModel) {
            
            [CityManager shareManager].currentShowCityModel = saveCityModel;

            // 如果已经保存过城市，则重新定位，如果定位城市与保存城市不一样，则提示是否切换城市
            [[LZMapLocationManager shareLocationManager] startLocationSuccess:^(CLLocation *aLocation, NSString *cityName) {
                CitysModel *locationCitymodel = [CityManager searchTheModelWithKeyWord:cityName];
                
                [CityManager shareManager].locationCityModel = locationCitymodel;
                
                if (![saveCityModel.cityNO isEqualToString:locationCitymodel.cityNO] || ![saveCityModel.name isEqualToString:locationCitymodel.name]) {
                    // 如果定位的城市和选择的城市不是同一个城市
                    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_location_not_same_city_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                    [alert show];
                    
                    alert.clickButtonIndexBlock = ^(NSInteger index) {
                        if (index == 1) {
                            [CityManager shareManager].currentShowCityModel = locationCitymodel;
                            [CitysModel setCityMessageWithCityEntity:locationCitymodel];
                        }
                    };
                }
            } Failed:^(NSError *error) {
                [CityManager shareManager].currentShowCityModel = saveCityModel;
            }];
        }
        else {
            // 如果没有保存过城市，则定位城市
            [[LZMapLocationManager shareLocationManager] startLocationSuccess:^(CLLocation *aLocation, NSString *cityName) {
                
                CitysModel *locationCitymodel = [CityManager searchTheModelWithKeyWord:cityName];
                
                [CityManager shareManager].locationCityModel = locationCitymodel;
                
                [CityManager shareManager].currentShowCityModel = locationCitymodel;
                
                [CitysModel setCityMessageWithCityEntity:locationCitymodel];
                
            } Failed:^(NSError *error) {
                [CityManager shareManager].currentShowCityModel = [CityManager returnDefaultCityWhenLocationFailed];
            }];
        }
    }
    else {
        // 如果没开定位
        if (saveCityModel) {
            // 如果已经保存过城市，则用保存过得城市
            [CityManager shareManager].currentShowCityModel = saveCityModel;
        }
        else {
            // 如果没有保存过城市，则提示用户去开启定位；如果用户不选择去设置开启定位，则用默认城市
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_permissions_address_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"iphone_permissions_go_setting", nil),nil];
            [alert show];
            
            alert.clickButtonIndexBlock = ^(NSInteger index) {
                if (index == 0) {
                    [CityManager shareManager].currentShowCityModel = [CityManager returnDefaultCityWhenLocationFailed];
                } else {
                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }
            };
        }
    }
}

- (void)startLocationSuccess:(LocationUpdateCompletion)completionBlock Failed:(LocationFailedBlock)faildBlock
{
    self.completionBlock = completionBlock;
    self.failedBlock = faildBlock;
    
    [self.locationManager startUpdatingLocation];
}

- (BOOL)isOpenLocation {
    
    if ([CLLocationManager locationServicesEnabled] == NO || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        // 如果没有开启定位
        return NO;
    }
    
    return YES;
}

#pragma mark - delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    // 添加位置和精度之间的时间跨度,以防止多次被调用下面的逻辑
    CLLocation *newLocation = locations.lastObject;
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 5.0) return;
    if (newLocation.horizontalAccuracy < 0) return;
    
    CLLocation *location=[locations firstObject];//取出第一个位置
    self.currentLocation = location;
    WS(wSelf);
    //反地理编码
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        CLPlacemark *placemark=[placemarks firstObject];
        NSString *cityName = placemark.locality;
        DLog(@"*******==%@",cityName);
        wSelf.cityName = cityName;
        if (wSelf.completionBlock) {
            wSelf.completionBlock(location,cityName);
        }
        
    }];

    //如果不需要实时定位，使用完即使关闭定位服务
    [self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    // 定位可用，但是定位失败了
    if (self.failedBlock) {
        self.failedBlock(error);
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if ([CLLocationManager locationServicesEnabled] == NO || status == kCLAuthorizationStatusDenied) {
        DLog(@"====未开启定位 or 未允许定位")
        return;
    }
}

#pragma mark - private method

@end
